<template>
    <van-nav-bar :fixed="true" left-text="返回" left-arrow @click-left="back">
        <template #right>
            <van-search v-model="keyword" show-action placeholder="输入商品关键字" :autofocus="true" autocomplete="off"
                shape="round" @input="search" @search="search" />
        </template>
    </van-nav-bar>

    <div class="search-box" v-show="keywords.length > 0">
        <div class="box-content">
            <div class="box-search" v-for="(item, index) in keywords" :key="index" @click="quickSearch(item.title)">
                <div>{{ item.title }}</div>
                <div @click="removeOne(index)">x</div>
            </div>


        </div>
        <div class="box-btn" @click="clearAll">
            清除所有搜索历史
        </div>
    </div>

    <div class="pro-box">
        <div class="pro-item" v-for="(item, index) in products" :key="index" @click="viewDetail(item.pid)">
            <Product :pro="item" />
        </div>
    </div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router'

import { getsearch } from '@/api/index'

import Product from "@/components/Product.vue"
import { Toast } from 'vant';


let router = useRouter();

let keyword: any = ref<string>('');

//定时器序号
let timer: any = -1;

//商品数据
let products: any = ref<Array<any>>([]);

//所有搜索过的关键字, 最多10个
let keywords: any = ref<Array<string>>([]);

//输入关键字搜索
let search: () => void = (): void => {
    //使用函数防抖控制触发函数执行的频率
    clearTimeout(timer);
    timer = setTimeout(() => {

        //获取输入商品名称关键字
        searchProduct();

    }, 580);

}

//查看商品详情
let viewDetail: (pid: string) => void = (pid: string): void => {
    router.push({ name: "Detail", params: { pid } });
}

//点击搜索关键字进行快速搜索
let quickSearch: (kw: string) => void = (kw: string): void => {

    if (keyword.value === kw) {

        return;
    }
    keyword.value = kw;
    searchProduct();
}

let back: () => void = (): void => {
    router.go(-1);
}

//删除所有搜索关键字
let clearAll: () => void = (): void => {
    //清空数组
    keywords.value = [];
    localStorage.setItem("historySearch", JSON.stringify(keywords.value));
}

//搜索商品
let searchProduct: () => void = (): void => {
    if (keyword.value.trim() === "") {
        return;
    }



    getsearch({

        name: keyword.value,
    })
        .then((result: any): void => {


            if (result.data.code === "Q001") {
                products.value = result.data.result;

                if (result.data.result.length > 0) {
                    //验证是否存在重复的关键字
                    for (let i = 0; i < keywords.value.length; i++) {
                        if (keywords.value[i].title === keyword.value) {
                            return;
                        }
                    }

                    //是否搜索关键字超出10个, 则移除第一个关键字
                    if (keywords.value.length === 15) {
                        keywords.value.splice(0, 1);
                    }

                    keywords.value.push({ title: keyword.value });
                    localStorage.setItem(
                        "historySearch",
                        JSON.stringify(keywords.value)
                    );


                } else {
                    Toast('查无此物，请重新输入')
                }
            }
        })

}



//单个删除关键字
let removeOne: (index: number) => void = (index: number): void => {

    keywords.value.splice(index, 1);
    localStorage.setItem("historySearch", JSON.stringify(keywords.value));
}

onMounted(() => {
    //获取搜索历史记录
    let historySearch: string | null = localStorage.getItem("historySearch");

    if (historySearch) {
        keywords.value.push(...JSON.parse(historySearch));
    }
})
</script>
<style lang="less" scoped>
.search-box {
    width: 100vw;
    height: auto;
    padding: 10px;
    margin-top: 50px;
    background-color: rgb(255, 255, 255);

    .box-content {
        width: 100%;
        height: auto;
        display: flex;
        flex-wrap: wrap;
        // background-color: aquamarine;

        .box-search {
            min-width: 10px;
            margin-top: 10px;
            margin-left: 10px;
            border-radius: 5px;
            padding: 4px;
            display: flex;
            font-size: 12px;
            background-color: #e8e8e8;
            justify-content: center;
            align-items: center;

            & :nth-child(2) {
                display: flex;
                justify-content: center;
                align-items: center;
                margin-left: 5px;
                margin-right: 5px;
            }
        }
    }





    .box-btn {
        width: 160px;
        height: 30px;
        display: flex;
        margin: 15px auto;
        margin-top: 30px;
        border-radius: 5px;
        justify-content: center;
        align-items: center;
        background-color: #e8e8e8;
    }
}

.pro-box {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
}

.pro-item {
    width: calc(~"50% - 10px + 10px / 2 - 20px");
    background-color: #fff;
    margin-bottom: 10px;
    margin-right: 10px;
    padding: 10px;

    &:nth-child(2n) {
        margin-right: 0;
    }
}

// .bg-cover {}
</style>